package com.zhuhjay.chat.server;

import com.zhuhjay.chat.config.Config;
import com.zhuhjay.chat.protocol.MessageCodecSharable;
import com.zhuhjay.chat.protocol.ProcotolFrameDecoder;
import com.zhuhjay.chat.server.handler.AbstractRequestMessageHandler;
import com.zhuhjay.chat.server.handler.HeartbeatDetectionHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ZhuHJay
 */
@Slf4j
public class ServerBoot {

    private final NioEventLoopGroup boss = new NioEventLoopGroup();
    private final NioEventLoopGroup worker = new NioEventLoopGroup();

    private final MessageCodecSharable messageCodec = new MessageCodecSharable();
    private final HeartbeatDetectionHandler heartbeatHandler = new HeartbeatDetectionHandler();
    private final LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);

    /** 启动端口 **/
    private final int port;

    public ServerBoot() {
        this(Config.getPort());
    }

    public ServerBoot(int port) {
        this.port = port;
    }

    public void run() {
        new ServerBootstrap()
                .channel(NioServerSocketChannel.class)
                .group(boss, worker)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ProcotolFrameDecoder());
                        if (Config.isDebug()) {
                            ch.pipeline().addLast(loggingHandler);
                        }
                        ch.pipeline().addLast(messageCodec);
                        ch.pipeline().addLast(new IdleStateHandler(5, 0, 0));
                        ch.pipeline().addLast(heartbeatHandler);
                        AbstractRequestMessageHandler.SHARABLE_HANDLERS.forEach(handler -> ch.pipeline().addLast(handler));
                    }
                }).bind(port).channel()
                .closeFuture().addListener(future -> {
                    boss.shutdownGracefully();
                    worker.shutdownGracefully();
                });
    }

}
